﻿using Common.Communal;
using ERP.Domain.System;
using MediatR;
using SqlSugar;
using System.Api.Read.Applications.Commands.Users;
using System.DTO;

namespace System.Api.Read.Applications.CommandHandlers.Users
{
    /// <summary>
    /// 用户登录命令处理程序
    /// </summary>
    public class UserLoginCommandHandler : IRequestHandler<UserLoginCommand, ApiResult<UserDTO>>
    {
        /// <summary>
        /// SqlSugar客户端
        /// </summary>
        private readonly ISqlSugarClient sqlSugar;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sqlSugar">SqlSugar客户端</param>
        public UserLoginCommandHandler(ISqlSugarClient sqlSugar)
        {
            this.sqlSugar = sqlSugar;
        }
        /// <summary>
        /// 处理用户登录命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回结果</returns>
        public Task<ApiResult<UserDTO>> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            ApiResult<UserDTO> result = new ApiResult<UserDTO>();
            var query = sqlSugar.Queryable<User>().
                LeftJoin<Post>((a,b)=>a.PostNo==b.PostNo).
                LeftJoin<Organize>((a,b,c)=>a.OrganzationNo==c.OrganizeNo).
                Where((a,b,c) => a.UserAccount == request.UserAccount && a.UserPassword == request.UserPassword && a.IsDeleted == false).
                Select((a, b, c) => new UserDTO
                {
                    Id = a.Id,
                    UserNo = a.UserNo,
                    UserName = a.UserName,
                    UserAccount = a.UserAccount,
                    PostNo = a.PostNo,
                    PostName = b.PostName,
                    OrganzationNo = a.OrganzationNo,
                    OrganizeName = c.OrganizeName,
                    UserPhone = a.UserPhone,
                    UserEmail = a.UserEmail,
                    IsDeleted = a.IsDeleted
                }).First();
            if (query != null)
            {
                result.Success(query, result.Message = "登录成功");
            }
            else
            {
                result.Error(result.Message = "登录失败，用户名或密码错误");
            }
            return Task.FromResult(result);
        }
    }
}
